package com.gcxy.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcxy.conf.result.PageVO;
import com.gcxy.conf.result.R;
import com.gcxy.dto.PenAddDTO;
import com.gcxy.dto.PenPageDTO;
import com.gcxy.dto.PenUpdateDTO;
import com.gcxy.entity.DataDicVal;
import com.gcxy.entity.Pen;
import com.gcxy.entity.Ranch;
import com.gcxy.entity.User;
import com.gcxy.mapper.PenMapper;
import com.gcxy.service.IPenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.service.IRanchService;
import com.gcxy.service.IUserService;
import com.gcxy.vo.PenVO;
import com.gcxy.vo.RanchVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 圈舍管理 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-25
 */
@Service
public class PenServiceImpl extends ServiceImpl<PenMapper, Pen> implements IPenService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRanchService ranchService;

    @Override
    public R addPen(PenAddDTO penAddDTO) {
        Object userIdObj = StpUtil.getLoginId();
        String userId = (String) userIdObj;
        LambdaQueryWrapper<Ranch> ranchLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ranchLambdaQueryWrapper.eq(Ranch::getRanchName, penAddDTO.getRanchName());
        Ranch ranch = ranchService.getOne(ranchLambdaQueryWrapper);
        if (ranch == null) {
            return R.Failed("该牧场不存在");
        }
        if (ranch.getRanchStatus()!=1){
            return R.Failed("该牧场已被停用");
        }
        LambdaQueryWrapper<Pen> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Pen::getRanchId, ranch.getRanchId())
                .eq(Pen::getPenName, penAddDTO.getPenName());
        Pen pen = getOne(queryWrapper);
        if (pen != null) {
            return R.Failed("该圈舍已存在");
        }
        Pen pen1=new Pen();
        pen1.setRanchId(ranch.getRanchId());
        pen1.setPenName(penAddDTO.getPenName());
        LocalDateTime now = LocalDateTime.now();
        pen1.setCreater(userService.getById(userId).getUserName());
        pen1.setCreateTime(now);
        pen1.setPenStatus(1);
        pen1.setAmountLivestock(0);
        pen1.setUpdater(userService.getById(userId).getUserName());
        pen1.setUpdateTime(now);
        save(pen1);
        return R.Success("新增成功！");
    }

    @Override
    public R deletePen(String id) {
        removeById(id);
        return R.Success("删除成功");
    }

    @Override
    public R changePenStatus(String id) {
        Pen pen = getById(id);
        if (pen == null) {
            return R.Failed("未找到对应的圈舍");
        }
        if (pen.getPenStatus() == 1) {
            if (pen.getAmountLivestock()!=0){
                return R.Failed("有未出栏状态的牲畜,不能停用");
            }
            pen.setPenStatus(0);
        }else {
            pen.setPenStatus(1);
        }
        LocalDateTime now = LocalDateTime.now();
        Object userIdObj = StpUtil.getLoginId();
        String userId = (String) userIdObj;
        pen.setUpdater(userService.getById(userId).getUserName());
        pen.setUpdateTime(now);
        updateById(pen);
        return R.Success("修改成功");
    }

    @Override
    public R getPenById(String id) {
        return R.Success(this.getPenById(id));
    }

    @Override
    public R updatePen(PenUpdateDTO penUpdateDTO) {
        Pen pen=this.getById(penUpdateDTO.getPenId());
        BeanUtils.copyProperties(penUpdateDTO, pen);
        LocalDateTime now = LocalDateTime.now();
        Object userIdObj = StpUtil.getLoginId();
        String userId = (String) userIdObj;
        pen.setUpdater(userService.getById(userId).getUserName());
        pen.setUpdateTime(now);
//        pen.setCreater(userService.getById(userId).getUserName());
//        pen.setCreateTime(now);
        updateById(pen);
        return R.Success("修改成功");
    }

    @Override
    public R getPenList(PenPageDTO penPageDTO) {
        List<Ranch> ranchList = new ArrayList<>();
        if (penPageDTO.getRanchName()!= null) {
            LambdaQueryWrapper<Ranch> ranchLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 使用 like 方法进行模糊查询，添加通配符
            String ranchName = "%" + penPageDTO.getRanchName() + "%";
            ranchLambdaQueryWrapper.like(penPageDTO.getRanchName()!= null, Ranch::getRanchName, ranchName);
            // 获取满足条件的 ranch 列表
            ranchList = ranchService.list(ranchLambdaQueryWrapper);
        }
        LambdaQueryWrapper<Pen> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(penPageDTO.getPenName()!= null, Pen::getPenName, penPageDTO.getPenName())
                .eq(penPageDTO.getPenStatus()!= null, Pen::getPenStatus, penPageDTO.getPenStatus());
        if (!ranchList.isEmpty()) {
            List<Integer> ranchIds = new ArrayList<>(); // 存储 ranch 的 RanchId
            for (Ranch ranch : ranchList) {
                if (ranch.getRanchId()!= null) {
                    ranchIds.add(ranch.getRanchId());
                }
            }
            // 使用 in 方法将所有 ranch 的 RanchId 加入到查询条件中
            queryWrapper.in(!ranchIds.isEmpty(), Pen::getRanchId, ranchIds);
        }
        Page<Pen> penPage = new Page<>(penPageDTO.getPageNumber(), penPageDTO.getPageSize());
        penPage = page(penPage, queryWrapper);
        PageVO<PenVO> penVOPageVO = new PageVO<>();
        BeanUtils.copyProperties(penPage, penVOPageVO);
        List<Pen> penList = penPage.getRecords();
        List<PenVO> penVOList = new ArrayList<>();
        for (Pen pen : penList) {
            PenVO penVO = new PenVO();
            BeanUtils.copyProperties(pen, penVO);
            LambdaQueryWrapper<Ranch> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(penVO.getRanchId()!= null, Ranch::getRanchId, penVO.getRanchId());
            Ranch ranch1 = ranchService.getOne(queryWrapper1);
            penVO.setRanchName(ranch1.getRanchName());
            penVOList.add(penVO);
        }
        penVOPageVO.setRecords(penVOList);
        return R.Success(penVOPageVO);
    }
}
